import { FavoriteBorderOutlined } from '@mui/icons-material';
import {
  Badge,
  Button,
  IconButton,
  ImageListItem,
  ImageList as MuiImageList,
} from '@mui/material';
import { useModel } from '@umijs/max';
import { Image, Tag } from 'antd';

type ItemProps = {
  img: string;
  id: number;
  name: string;
  type: string;
  tag: Array<string>;
  imageUrl: string;
};

type TemplateInfo = {
  id: number;
  type: 'SHARE_TEMPLATE';
  name: string;
};

function fallbackCopyToClipboard(text: string) {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  textarea.style.position = 'fixed'; // 避免滚动到底部
  document.body.appendChild(textarea);
  textarea.select();

  try {
    const successful = document.execCommand('copy');
    if (!successful) {
      console.error('复制命令执行失败');
      return false;
    }
    console.log('使用execCommand复制成功');
    return true;
  } catch (err) {
    console.error('无法复制文本: ', err);
    return false;
  } finally {
    document.body.removeChild(textarea);
  }
}

function copyToClipboard(info: TemplateInfo) {
  const text = JSON.stringify(info);

  // 优先使用 Clipboard API
  if (navigator.clipboard) {
    return navigator.clipboard
      .writeText(text)
      .then(() => {
        console.log('使用Clipboard API复制成功');
        return true;
      })
      .catch((err) => {
        console.error('Clipboard API失败，尝试使用execCommand', err);
        return fallbackCopyToClipboard(text);
      });
  }

  // 回退到execCommand
  return fallbackCopyToClipboard(text);
}

export const List = () => {
  const { list = [] } = useModel('list');
  const itemData = list?.map<ItemProps>((item: ItemProps) => ({
    img: 'https://images.unsplash.com/photo-1551963831-b3b1ca40c98e',
    name: item.name,
    id: item.id,
    tag: item.tag,
    type: item.type,
    imageUrl: item.imageUrl,
  }));

  return list?.length ? (
    <MuiImageList sx={{ padding: '20px' }} cols={8} gap={20}>
      {itemData.map((item) => (
        <ImageListItem key={item.id}>
          <Image
            src={`${item.imageUrl}`}
            height={'100%'}
            alt={item.name}
            loading="lazy"
            fallback={
              ''
            }
          />
          <div>
            <IconButton>
              <Badge color="secondary" badgeContent={5}>
                <FavoriteBorderOutlined />
              </Badge>
            </IconButton>
          </div>
          <div>
            {item.tag.map((ret) => (
              <Tag key={ret}>{ret}</Tag>
            ))}
          </div>
          <div>{item.name}</div>
          <div>
            <Button
              variant="contained"
              onClick={() => {
                copyToClipboard({
                  id: item.id,
                  type: 'SHARE_TEMPLATE',
                  name: item.name,
                });
              }}
            >
              使用
            </Button>
          </div>
        </ImageListItem>
      ))}
    </MuiImageList>
  ) : null;
};
